//作用：操作读卡器[*****钱包和积分应用分开之后的版本*****支持非接触式*****支持LANDI STAR-758密码键盘*****]
//作者：dzm
//时间：2007-9
document.write("<object id=\"XEnroll\" classid=\"clsid:127698e4-e730-4e5c-a2b1-21490a70c8a1\" width=0 height=0 align=center hspace=0 vspace=0></object>");//安装证书的组件(Windows下)
window.onunload = function(){releaseCard()}
var hCard=0 ;//卡片句柄
var ED_LOAD = 1	;
var EP_LOAD = 2;
var defaultPin = "123456";
var NOT_USE_PIN = "00";
var USE_PIN = "01";
var keypadWaitTime = 30000; //密码键盘超时时长(毫秒)
var KEY_INDEX = 1 ;//密钥索引
var ActiveXVer="1,0,4,6"; //ActiveX控件版本
var CARD_ITEMS = new Array();
CARD_ITEMS[0] = ["asn","卡号"];
CARD_ITEMS[1] = ["cardType","卡类型"];
CARD_ITEMS[2] = ["name","用户名"];
CARD_ITEMS[3] = ["certNo","证件号码"];
CARD_ITEMS[4] = ["cardBalance","卡余额"];
CARD_ITEMS[5] = ["cardLoyaltyBalance","卡积分余额"];
CARD_ITEMS[6] = ["overdueLoyaltyBalance","过期积分余额"];
CARD_ITEMS[7] = ["cmd","积分交易字符串"];
CARD_ITEMS[8] = ["offlineTxNo","脱机交易序列号"];
CARD_ITEMS[9] = ["onlineTxNo","联机交易序列号"];
CARD_ITEMS[10] = ["random","伪随机数"];
CARD_ITEMS[11] = ["macData","MAC1"];
//限制信息
CARD_ITEMS[12] = ["petroLimit","油品限制"];
CARD_ITEMS[13] = ["goodLimit","商品限制"];
CARD_ITEMS[14] = ["unitLimit","定点单位限制"];
CARD_ITEMS[15] = ["timesLimit","每天加油次数限制"];
CARD_ITEMS[16] = ["amountLimit","每日加油总金额限制"];
CARD_ITEMS[17] = ["carNoLimit","车号限制"];
CARD_ITEMS[18] = ["areaLimit","限制区域"];
CARD_ITEMS[19] = ["pinFunction","PIN码功能支持标识"];
CARD_ITEMS[20] = ["payMethod","算方式标志"];
CARD_ITEMS[21] = ["petroCode","油品代码"];
CARD_ITEMS[22] = ["accountCode","客户编码"];
CARD_ITEMS[23] = ["unitCode","单位用户的单位代码"];
CARD_ITEMS[24] = ["issuerCity","发卡区域"];
CARD_ITEMS[25] = ["canOpenProvince","可开通省"];


//新规范

CARD_ITEMS[39] = ["oneDayTimesLimit","每天加油次数限制"];
CARD_ITEMS[40] = ["oneDayAmountLimit","每日加油总金额限制"];
CARD_ITEMS[41] = ["oneTimesAmountLimit","每次消费金额限制"];
CARD_ITEMS[42] = ["oneDayNumLimit","每日加油数量限制"];
CARD_ITEMS[43] = ["oneTimesNumLimit","每次加油数量限制"];
CARD_ITEMS[44] = ["frequencyLimit","加油频率限制"];
CARD_ITEMS[45] = ["whiteLimit","限站信息"];
	
	


//公共信息
CARD_ITEMS[26] = ["issuId","发卡方"];
CARD_ITEMS[27] = ["appType","应用类型"];
CARD_ITEMS[28] = ["appVersion","应用版本"];
CARD_ITEMS[29] = ["appStartDate","应用启用日期"];
CARD_ITEMS[30] = ["appStopDate","应用有效日期"];
CARD_ITEMS[31] = ["FCIData","自定义FCI数据"];
//卡密码
CARD_ITEMS[32] = ["pin","卡密码"];
CARD_ITEMS[37] = ["usePin","是否启用卡密码"]


//新加
CARD_ITEMS[33] = ["invoiceKind","开票类型标志"];
CARD_ITEMS[34] = ["unitFinanceCode","单位财务编码"];

//cardreader
CARD_ITEMS[35] = ["posNo","终端编号"];
CARD_ITEMS[36] = ["posSn","终端流水号"];

//
CARD_ITEMS[38] = ["validDate","积分联机解扣计算MAC1的积分有效期"];
var AID1="A000000003504554524F4348494E41" //钱包AID
var AID2="A0000000034C4F59414C5459";      //积分AID
var PSAMPSE = "315041592E5359532E4444463031"; //PSAM卡PSE
var pbocErrors = {
	e63C0:'验证PIN锁定',
	e63C1:'认证失败，还有认证一次',
	e63C2:'认证失败，还有认证二次',
	e6581:'EEPROM损坏，导致卡锁定',
	e6700:'Lc长度错误',
	e6901:'命令不接受(无效状态)',
	e6981:'当前文件不是透明文件',
	e6982:'不满足安全状态',
	e6983:'验证PIN锁定',
	e6984:'引用数据无效(未申请随机数)',
	e6985:'使用条件不满足',
	e6988:'安全信息(MAC)数据无效',
	e6A80:'数据域参数不正确',
	e6A81:'功能不支持',
	e6A82:'未找到文件',
	e6A83:'未找到记录',
	e6A84:'记录空间已满',
	e6A85:'Lc与TLV结构不匹配',
	e6A86:'P1、P2参数错',
	e6A88:'未找到密钥数据',
	e6D00:'命令不存在',
	e6E00:'CLA错',
	e9002:'卡片未发现',
	e9302:'MAC无效',
	e9303:'应用永久锁定',
	e9401:'金额不足',
	
	
	e:'请检查读卡器是否正确接入',
	e0:'无卡',
	e1:'找不到卡片',
	e2:'找不到卡片',
	
	eC:"密码键盘通信错误"
}
//*********************证书和控件的安装***********************************
try{
		var cardCom = new ActiveXObject("COMLOADCTRL.LoadCtrl");　//创建对象
		var comVer = cardCom.getVersion();
			if(comVer!=ActiveXVer) //版本不一致即要更新控件
			{
				document.write("<OBJECT ID=\"cardCom1\" classid=\"clsid:11181CD3-442B-4DA7-95EC-6F129FCA9A41\" codebase=\"../common/COMLoadCtrl.cab#version="+ActiveXVer+"\" width=0 height=0 align=center hspace=0 vspace=0></OBJECT>");
				cardCom = cardCom1;
			}
		}catch(e){　//发生异常，表示没有安装过控件，则安装证书和控件
			//安装证书. 如果不是信任站点会提示"潜在的脚本冲突".点击＂是＂
			var CA ="";
			CA = CA +"MIIDszCCApugAwIBAgIIJOG9OEqVKfgwDQYJKoZIhvcNAQEFBQAwZzELMAkGA1UE\n";
			CA = CA +"BhMCQ04xEDAOBgNVBAgTB0JlaWppbmcxEDAOBgNVBAcTB0JlaWppbmcxDjAMBgNV\n";
			CA = CA +"BAoTBUNBMzY1MSQwIgYDVQQDExtDQTM2NSBGcmVlIFJvb3QgQ2VydGlmaWNhdGUw\n";
			CA = CA +"HhcNMDEwNTEyMDg0MDQxWhcNMzEwNTA1MDg0MDQxWjBnMQswCQYDVQQGEwJDTjEQ\n";
			CA = CA +"MA4GA1UECBMHQmVpamluZzEQMA4GA1UEBxMHQmVpamluZzEOMAwGA1UEChMFQ0Ez\n";
			CA = CA +"NjUxJDAiBgNVBAMTG0NBMzY1IEZyZWUgUm9vdCBDZXJ0aWZpY2F0ZTCCASIwDQYJ\n";
			CA = CA +"KoZIhvcNAQEBBQADggEPADCCAQoCggEBAOUJiqnKIVBDD5tPkx7i4vZh/mB3j+es\n";
			CA = CA +"yP5py6xw7f2wD2FKWEx/LU0HmcZOUEkZR+e0d72gF135rB5fs4R/vW47vkFP70yW\n";
			CA = CA +"duk3Q98qeEBiCWj1oIqu63insQL2qJJ9+5xD3S38AWqxTpXzGLTrpvuJMNwAKJWq\n";
			CA = CA +"5RSMIbFl/yoCpgfVz+iIGP9gjf/+PJOF08ii6BOZFygRGkWY0c2PiuyBOXnyZccS\n";
			CA = CA +"NWFIVoWkRT4RyUU1ojjdbVj5zer0roHaCpkTRREf7+ZC3gUXEJOu2V7Mqp7oKPq/\n";
			CA = CA +"ZaslorsB1sKMyXWBWwIL9MsdHKlGYRdFDwW7FSbK/ifRFErOnk+6xzECAwEAAaNj\n";
			CA = CA +"MGEwHQYDVR0OBBYEFP5hdKPBS60rwHHDpaJMAAPZIMMcMA4GA1UdDwEB/wQEAwIB\n";
			CA = CA +"BjAfBgNVHREEGDAWhhRodHRwOi8vd3d3LmNhMzY1LmNvbTAPBgNVHRMBAf8EBTAD\n";
			CA = CA +"AQH/MA0GCSqGSIb3DQEBBQUAA4IBAQDMipz61e91bQhVeGXC9CdnG+DBoHWw2Lxs\n";
			CA = CA +"pbRLq3BXKh05uhJ2fvP50aqLOJV4iw5qb6YITW8LvSYf6tfgXPj+axwP84ukBgYg\n";
			CA = CA +"29FcfWbVKW6PxQllGTi2LgvExTp6Aq8HTDDri5ElUItvGtDRAjKNgTASemzDtpuf\n";
			CA = CA +"OIFhom9Y6JPkxUfOSOWHfV18Tx2X5OJLcD/hqp5cb6f5C9YN6kl4Jz7/kZO1aiP0\n";
			CA = CA +"0Vmdf5wqLLavqEozhg0ZNbdgzvVJnleGpFYnj2ZbKLcdm7wUl0/JfC4/wIfRaSTB\n";
			CA = CA +"6k0u/zp4yTkexhb1rOVHKdHUIyC3/uq4afQcSwGTA1Hb47+jtdOd\n";	
			try{
				XEnroll.installPKCS7(CA);//安装证书
				document.write("<OBJECT ID=\"cardCom1\" classid=\"clsid:11181CD3-442B-4DA7-95EC-6F129FCA9A41\" codebase=\"../common/COMLoadCtrl.cab#version="+ActiveXVer+"\" width=0 height=0 align=center hspace=0 vspace=0></OBJECT>");
				cardCom = cardCom1;
			}catch(e)
			{
				throw new Error("没有证书安装或者控件,您将不能使用部分功能!");
			}

	}
	
	
	
window.onload = function()
{
	cardCom.installDriver(); 
}
function initActiveX() //安装读卡器驱动
{
	try{
	//cardCom.installDriver();       //安装读卡器驱动
	}catch(e)
	{
		showError("没有安装控件,"+e.description);
	}
}

//**************************end*********************************

var Card = {}

function releaseCard(){    //释放句柄
	if (hCard!=0)
	{cardCom.releaseCard(hCard);}		
}

function evalCardReturn(rsp){  //处理控件返回值
	var msg ;
	rsp = trim(rsp);
	var prefix = rsp.substring(0,2);
	if (prefix=='00'){
		return rsp.substring(2);	
	}
	var err = 'e'+rsp.toUpperCase();
	msg = pbocErrors[err];
	if (!msg) msg = '未知卡片错误:'+rsp;
	throw new Error(msg);
}


function getCard(){ //获得句柄
	//getPGApp();	
}


function getPGApp() //钱包应用
{
	cardCom.setKeyIndex(KEY_INDEX);//设置密钥索引
	hCard = evalCardReturn(String(cardCom.GetCard(AID1)));
}

function getLYApp() //积分应用
{
	cardCom.setKeyIndex(KEY_INDEX);//设置密钥索引
	hCard = evalCardReturn(String(cardCom.GetCard(AID2)));
	
}

function getChallenge(){
	return evalCardReturn(cardCom.getChallenge(hCard)).substring(0,8).toUpperCase();	
}

function appUnBlock() //钱包应用解锁
{		
		var rnd = getRandom(); //获取随机数
		var asn = getAsn();
		var result = DWR.syncCall('pbocService.appUnblock',asn,"",rnd);
		evalCardReturn(cardCom.appUnblock(hCard,result.toUpperCase()));
}

function appLYUnBlock()//积分应用解锁
{
		var rnd = getLYRandom(); //获取积分应用随机数
		var asn = getAsn();
		var result = DWR.syncCall('pbocService.appUnblock',asn,"",rnd);
		evalCardReturn(cardCom.appUnblock(hCard,result.toUpperCase()));
}

function getAsn(){    //获得卡片应用序列号
	return
	// getCardSN没有返回00前缀
	var asn = cardCom.getCardSN(hCard).substring(4);
	if(asn!="0000000000000000"&&asn!="CDCDCDCDCDCDCDCD")
		return asn;
	else
	throw new Error("使用条件不满足");
}

function getPsamTN()
{
	var re = evalCardReturn(cardCom.getPsamTN(PSAMPSE));
	if(re.indexOf("9F0C")<40)
	{
		throw new Error("不是PSAM卡");
	}
	re = re.toUpperCase().split("9F0C")[1];
	re = re.substr(2,parseInt(re.substr(0,2),16)*2);
	var data={}
	data.PsamSN = re.substr(4,16); //PSAM序列号
	data.PsamVer = re.substr(20,2);//PSAM版本号
	data.KeyCardKind = re.substr(22,2);//密钥卡类型
	data.CommandVer = re.substr(24,2);//指令集版本
	data.FCI = re.substr(26,2);//发卡行自定义FCI数据
	data.PsamTN = re.substr(28,12);//终端机编号
	return data;
}


function verifyPin(pin)//验证密码
{
	evalCardReturn(cardCom.verifyPin(hCard,pin));
}


function getPin()  //获得从密码键盘输入的密码
{	
	var pin = evalCardReturn(cardCom.getKeypad(0,0));
	Loading.cancelBlockScreen();
	if(pin=="err")
	{
		throw new Error("从密码键盘获得密码发生错误!");
	}
	if(pin.length==0)
	{
		throw new Error("用户无输入或已取消输入!");
	}
	return pin;
}


function getCardPersonInfo(){   //获得持卡人信息
	var ret = evalCardReturn(cardCom.getCardInfo(hCard))
	var data = {}
	var arrdata=ret.split(",");
	//data[CARD_ITEMS[1][0]] = parseInt(arrdata[0],16);//卡类型
//	data[CARD_ITEMS[2][0]]=trim(arrdata[5]);//卡用户名称
	//data[CARD_ITEMS[3][0]]=trim(arrdata[6]);
	
	//data.cardKind=parseInt(arrdata[0],16);
	data.cardKind=parseInt(arrdata[0],16);
	data.contractKind=trim(arrdata[1]);
	data.clientCurrentGrade=trim(arrdata[2]);
	data.ifWhite=trim(arrdata[3]);	
	data.bankUserID=trim(arrdata[4]);
	data.userName=trim(arrdata[5]);
	data.userCID=trim(arrdata[6]);
	data.userCKind=trim(arrdata[7]);
	data.RFU=trim(arrdata[8]);
	
	return data
}

//个人化
function personal(cardKind,contractKind,clientCurrentGrade,ifWhite,bankUserID,userName,userCID,userCKind,RFU,pin) //个人化
{	
	getCard();
	var re ;	
	var asn = getAsn();
	var rnd = getRandom(); //获取随机数  
	rnd=rnd.substring(0,8).toUpperCase();
	//把数据用逗号","隔开，传到后台进行转换
	var data={}
	data.baseCardType = cardKind;
	data.contractType = contractKind;
	data.currentLevel = clientCurrentGrade;
	data.internal = bankUserID;
	data.name = userName;
	data.idno = userCID;
	data.idnoType = userCKind;
	data.RFU = RFU;
	var datamac = DWR.syncCall('pbocService.personalize',asn,data,rnd);
	var carddata = datamac.substr(0,150).toUpperCase(); //前150位
	var mac = datamac.substr(150,8).toUpperCase();      //后8位是MAC
	
	evalCardReturn(cardCom.personal(hCard,pin,carddata,mac));		
}


function getPublicInfo(hCard)　　　　//获取卡片公共信息
{
	var pInfo = evalCardReturn(cardCom.getPublicInfo(hCard));
	var data = {};
	data[CARD_ITEMS[26][0]] = pInfo.substring(0,16);
	data[CARD_ITEMS[27][0]] = pInfo.substring(16,18);
	data[CARD_ITEMS[28][0]] = pInfo.substring(18,20);
	data[CARD_ITEMS[0][0]]  = pInfo.substring(20,40);
	data[CARD_ITEMS[29][0]] = pInfo.substring(40,48);
	data[CARD_ITEMS[30][0]] = pInfo.substring(48,56);
	data[CARD_ITEMS[31][0]] = pInfo.substring(56,60);
	return data;
}

function getOfflineTxNo(pin){  //获得脱机交易序号
	var ret = evalCardReturn(cardCom.initPurchase(hCard,pin,0,ED_LOAD))
	return parseInt(ret.substr(8,4),16) - 1
}

function getOnlineTxNo(pin){   //获得联机交易序号
	var ret = evalCardReturn(cardCom.Init4Load(hCard,pin,1,ED_LOAD))
	return parseInt(ret.substr(8,4),16);
}

function getOfflineLyTxNo(pin){ //获得积分脱机交易序号  
	getLYApp();    
	var ret = evalCardReturn(cardCom.initLoyaltyPurchase(hCard,pin,0,"200808"));
	return parseInt(ret.substr(8,4),16) - 1
}

function getOnlineLyTxNo(pin){  //获得积分联机交易序号
	getLYApp();
	var ret = evalCardReturn(cardCom.initLoyaltyUnload(hCard,0,1,"200801",pin));
	return parseInt(ret.substr(8,4),16);
}



function init4Load(pin,amount,EPorED){  //圈存初始化
	if(!EPorED)EPorED=ED_LOAD
	var ret = evalCardReturn(cardCom.Init4Load(hCard,pin,amount,EPorED));	
	var data = {}
	data[CARD_ITEMS[4][0]] = parseInt(ret.substr(0,8),16);//ET余额
	data[CARD_ITEMS[9][0]] = parseInt(ret.substr(8,4),16);//ET联机交易序号
	data[CARD_ITEMS[10][0]] = ret.substr(16,8);//伪随机数（IC卡）
	data[CARD_ITEMS[11][0]] = ret.substr(24,8);//MAC1
	return data;
}
function init4UnLoad(pin,amount){ //圈提初始化
	var ret = evalCardReturn(cardCom.initUnLoad(hCard,amount,pin));
	var data = {}
	data[CARD_ITEMS[4][0]] = parseInt(ret.substr(0,8),16);//ET余额
	data[CARD_ITEMS[9][0]] = parseInt(ret.substr(8,4),16);//ET联机交易序号
	data[CARD_ITEMS[10][0]] = ret.substr(16,8);//伪随机数（IC卡）
	data[CARD_ITEMS[11][0]] = ret.substr(24,8);//MAC1
	return data
}
function credit4Load(serverDate,serverTime,mac2){ //圈存
	evalCardReturn(cardCom.Credit4Load(hCard,serverDate,serverTime,mac2))
	
}
function debit4Unload(serverDate,serverTime,mac2){ //圈提
	var ret = evalCardReturn(cardCom.unLoad(hCard,serverDate,serverTime,mac2))
	return ret.substring(0,8)
}

function init4LoyaltyLoad(pin,tradeDate,cmd)  //积分圈存初始化
{
	getLYApp();
	tradeDate = formatdate(tradeDate);
	var ret = evalCardReturn(cardCom.init4LoyatyLoad(hCard,pin,tradeDate,cmd.toUpperCase()));
	var data = {}
	data[CARD_ITEMS[5][0]] = parseInt(ret.substr(0,8),16);//有效积分余额(交易前)
	data[CARD_ITEMS[6][0]] = parseInt(ret.substr(8,8),16);//过期积分余额（交易前）
	data[CARD_ITEMS[9][0]] = parseInt(ret.substr(16,4),16);//联机交易序号
	data[CARD_ITEMS[10][0]] = ret.substr(24,8);//伪随机数（IC卡）
	data[CARD_ITEMS[11][0]] = ret.substr(32,8);//MAC1	4	
	data[CARD_ITEMS[7][0]] = cmd;
	return data
}

function credit4LoyaltyLoad(ret)  //积分圈存
{
	var re =evalCardReturn(cardCom.loyaltyLoad(hCard,ret.serverTime.substring(0,8),ret.serverTime.substring(8),ret.mac2.toUpperCase()));	
	return re.substring(0,8);			
}

function init4LoyaltyUnload(pin,amount,tradeDate) //积分圈提初始化
{
	getLYApp();
	tradeDate = formatdate(tradeDate);
	var ret = evalCardReturn(cardCom.initLoyaltyUnload(hCard,amount,1,tradeDate,pin));
	var data = {}
	data[CARD_ITEMS[5][0]] = parseInt(ret.substr(0,8),16);//积分余额
	data[CARD_ITEMS[9][0]] = parseInt(ret.substr(8,4),16);//联机交易序号
	data[CARD_ITEMS[10][0]] = ret.substr(16,8);//随机数
	data[CARD_ITEMS[11][0]] = ret.substr(24,8);
	return data
}

function debit4LoyaltyUnload(ret)   //积分圈提
{
	var ret = evalCardReturn(cardCom.loyaltyUnload(hCard,ret.serverTime.substring(0,8),ret.serverTime.substring(8),ret.mac2.toUpperCase()));
	return ret;
}

function expiredLoyalty(validDate,mac) //清除过期积分
{	
	var date = formatdate(validDate);
	var re = evalCardReturn(cardCom.expiredLoyalty(hCard,date,mac.toUpperCase()));
	return parseInt(re.substr(0,8),16);
}

function formatdate(date)  //积分圈存、圈提交易时间格式化
{
	date = date.substr(0,6);
	var year = date.substr(0,4);
	var myear = parseInt(year+"06");
	if(parseInt(date)>myear)
	{
		date = year+"02";
	}
	else
	{
		date = year+"01";
	}
	return date;
	
}

function getRandom(){   //获取随机数
	var rnd = cardCom.getChallenge(hCard); 
	rnd=rnd.substring(0,8).toUpperCase();
	return rnd;
}

function getLYRandom() //积分应用获取随机数
{
	getLYApp();
	var rnd = cardCom.getChallenge(hCard); 
	rnd=rnd.substring(0,8).toUpperCase();
	return rnd;
}


function getKeypad()  //从密码键盘获得密码
{
	var p = cardCom.getKeypad(hCard);
	if(p=="")
	throw new Error("请重新输入密码！");	
	else
	return p;
}

function getCardBalance(pin){    //查询存折余额
	return evalCardReturn(cardCom.GetBalance(hCard,pin,ED_LOAD))
}

function getLoyaltyBalance(tradeDate)   //查询当前积分余额,tradeDate:YYYYMM
{
	getLYApp();
	var ly = evalCardReturn(cardCom.getLoyaltyBalance(hCard,0,3,tradeDate));
	return ly;
}

function getInvalidLoyaltyBalance(tradeDate)   //查询当前无效积分,tradeDate:YYYYMM
{
	getLYApp();
	var invalidLy = evalCardReturn(cardCom.getLoyaltyBalance(hCard,3,3,tradeDate));
	return invalidLy;
}

function getBalance(pin,tradeDate)   //查询存在余额和积分余额，tradeDate:YYYYMM
{
	var data = {}
	data[CARD_ITEMS[4][0]] = getCardBalance(pin);  //存折余额
	data[CARD_ITEMS[5][0]] = getLoyaltyBalance(tradeDate) ;  //积分余额
	return data;
}


function getApplicationInfo(o) //查询加油应用业务信息文件
{
	var re = evalCardReturn(cardCom.getAppInfo(hCard));
	var dataarr = re.split(",");
	dataarr[7] = trim(dataarr[7]);
	dataarr[12] = trim(dataarr[12]);
	dataarr[13] = trim(dataarr[13]);
	var data ={}	
	if(o=="updatePinApp")
	data[CARD_ITEMS[12][0]] = dataarr[0];
	else
	data[CARD_ITEMS[12][0]] = dataarr[0];
	data[CARD_ITEMS[13][0]] = dataarr[1];
	data[CARD_ITEMS[39][0]] = dataarr[2]=="FF"?"FF":parseInt(dataarr[2],16);
	data[CARD_ITEMS[40][0]] = dataarr[3]=="FFFFFFFF"?"FFFFFFFF":parseInt(dataarr[3],16);
	//data[CARD_ITEMS[41][0]] = dataarr[4]=="FFFFFFFF"?"FFFFFFFF":parseInt(dataarr[4],16);
	data[CARD_ITEMS[42][0]] = dataarr[4]=="FFFF"?"FFFF":parseInt(dataarr[4],16);
	data[CARD_ITEMS[43][0]] = dataarr[5]=="FFFFFFFF"?"FFFFFFFF":parseInt(dataarr[5],16);
	data[CARD_ITEMS[44][0]] = dataarr[6]=="FF"?"FF":parseInt(dataarr[6],16);
	data[CARD_ITEMS[17][0]] = dataarr[7];  //车号限制
	data[CARD_ITEMS[19][0]] = dataarr[8];	//PIN码功能支持标识
	data[CARD_ITEMS[22][0]] = dataarr[9]=="FFFFFFFFFFFF"?"FFFFFFFFFFFF":parseInt(dataarr[9],16);//客户编码
	data[CARD_ITEMS[33][0]] = dataarr[10];      //开票类型标志
	data[CARD_ITEMS[23][0]] = dataarr[11];		//单位用户的单位代码
	data[CARD_ITEMS[24][0]] = dataarr[12];		//发卡地市
	data[CARD_ITEMS[18][0]] = dataarr[13];      //限制区域
	data[CARD_ITEMS[45][0]] = dataarr[14];      //限站信息
	
	return data;
}

function getTrans(pin,Tkind) //查询交易记录。参数：密码，交易类型(没有或者"00"代表所有类型)
{
	var arrTrans = new Array();
	var arrSelectTrans = new Array();
	var j=0;
	var re = evalCardReturn(cardCom.getTrans(hCard,pin,10)); //第3个参数控制读取几条记录，最大10
	var list=re.split("|");	
	var TSN;//ED或 EP联机或脱机交易序号
  	var limit;//透支限额
  	var money;//交易金额
  	var transType; //交易类型标识
  	var terminalNo;//终端机编号
  	var transDate;//交易日期（终端）
  	var transTime;//交易时间（终端）
	for(var i=0;i<list.length-1;i++)
	{
	  	TSN=list[i].substring(0,4);
    	limit=list[i].substring(4,10);
    	money=list[i].substring(10,18);
    	transType=list[i].substring(18,20);
    	terminalNo=list[i].substring(20,32);
    	transDate=list[i].substring(32,40);
		transTime=list[i].substring(40,46);
		arrTrans[i]=[TSN,limit,money,transType,terminalNo,transDate,transTime];
	}
	if(Tkind!=null&&Tkind!="00")
	{
		for(var i=0;i<list.length-1;i++)
		{
			if(String(arrTrans[i][3])==Tkind)
			{
				arrSelectTrans[j] = arrTrans[i];
				j++;
			}
		}
		if(arrSelectTrans.length==0)throw new Error("无交易记录！");	
		return arrSelectTrans;
	}
//	if(arrTrans.length==0)throw new Error("无交易记录！");	
	return arrTrans;	
}


function getLoyaltyTrans(pin,Tkind) //查询积分交易记录。参数：密码，交易类型(没有或者"00"代表所有类型)
{
	getLYApp();
	var arrTrans = new Array();
	var arrSelectTrans = new Array();
	var j=0;
	var re = evalCardReturn(cardCom.getLoyaltyTrans(hCard,pin,10)); //第3个参数控制读取几条记录，最大10
	var list=re.split("|");	
	var TSN;//ED或 EP联机或脱机交易序号
  	var money;//交易金额
  	var transType; //交易类型标识
  	var terminalNo;//终端机编号
  	var transDate;//交易日期（终端）
  	var transTime;//交易时间（终端）
	for(var i=0;i<list.length-1;i++)
	{		
		TSN=list[i].substring(0,4);
    	money=list[i].substring(4,12);
    	transType=list[i].substring(12,14);
    	terminalNo=list[i].substring(14,26);
    	transDate=list[i].substring(26,34);
		transTime=list[i].substring(34,40);
		arrTrans[i]=[TSN,"",money,transType,terminalNo,transDate,transTime];
	}
	if(Tkind!=null&&Tkind!="00")
	{
		for(var i=0;i<list.length-1;i++)
		{
			if(String(arrTrans[i][3])==Tkind)
			{
				arrSelectTrans[j] = arrTrans[i];
				j++;
			}
		}
		if(arrSelectTrans.length==0)throw new Error("无交易记录！");	
		return arrSelectTrans;
	}
//	if(arrTrans.length==0)throw new Error("无交易记录！");	
	return arrTrans;	
}

function hextobinary(hex,len)  //十六进制转2进制, hex十六进制数字,len返回的二进制长度
{	
	if(!len)len=24;
	var l = parseInt(hex,16);
	var b = cardCom.hextobinary(l);
	b = String(b);
	n = len-b.length;
	if(n>0)
	{
		for(var i=0;i<n;i++)
		{
			b = "0"+b;
		}
	} 
	return b;
}


//在把客户端数据送往后台的时候，先进行格式化
function formatAppInfo(spetroLimit,sgoodLimit,soneDayTimesLimit,soneDayAmountLimit,soneDayNumLimit,soneTimesNumLimit,sfrequencyLimit,scarNoLimit,spinFunction,saccountCode,sinvoiceKind,sunitCode,sissuerCity,sareaLimit,swhiteLimit)
{
	var appdata={}
	appdata[CARD_ITEMS[12][0]] = spetroLimit;       
	appdata[CARD_ITEMS[13][0]] = sgoodLimit;
	appdata[CARD_ITEMS[39][0]] = soneDayTimesLimit;
	appdata[CARD_ITEMS[40][0]] = soneDayAmountLimit;
	//appdata[CARD_ITEMS[41][0]] = soneTimesAmountLimit;
	appdata[CARD_ITEMS[42][0]] = soneDayNumLimit;
	appdata[CARD_ITEMS[43][0]] = soneTimesNumLimit;
	appdata[CARD_ITEMS[44][0]] = sfrequencyLimit;
	appdata[CARD_ITEMS[17][0]] = scarNoLimit.toUpperCase(); //车号限制
	appdata[CARD_ITEMS[19][0]] = F(spinFunction,2); 		//PIN码功能支持标识
	appdata[CARD_ITEMS[22][0]] = F(saccountCode,12);		//客户编码
	appdata[CARD_ITEMS[33][0]] = F(sinvoiceKind,2);         //开票类型标志
	appdata[CARD_ITEMS[23][0]] = F(sunitCode,12);			//单位用户的单位代码
	appdata[CARD_ITEMS[24][0]]=  sissuerCity;			//发卡地市
	appdata[CARD_ITEMS[18][0]]=  sareaLimit;			//限制地市
	appdata[CARD_ITEMS[45][0]] = swhiteLimit;           //限站信息
	return appdata;
}

function updateAppInfo(pin,cardData,mac)  //更新加油应用业务信息文件
{
	cardData = cardData + "FFFFFFFFFFFFFFFFFFFF";//补位
    evalCardReturn(cardCom.updateAppInfo(hCard,pin,cardData.toUpperCase(),mac.toUpperCase()));
}

function F(str,len)  //如果为str空，用len个"F"填充
{
	str = String(str);
	str = trim(str);
	if(str=="")
	{
		for(var i=0;i<len;i++)
		{
			str = str + "F";
		}
	}
	return str;
}

function stradd(str,len)
{
	if(str.length<len)
	{
		for(var i=0;i<len-length;i++)
		{
			str = "0" + str;
		}
		
	}
	return str;
	
}

// 读灰锁状态时,返回6985指"未发生过解扣和联机解扣交易",并不是"不满足使用条件",直接跳过此异常
function getLockProof(pin)  //读取卡片是否处于灰锁状态
{
    getCard();
	var re = cardCom.getLockProof(hCard,pin);
	if(re!="6985")re=evalCardReturn(re);
		if(re.substr(0,2)=="01")
		return true;
		else
		return false;	
}

function getLockProofData(pin)  //读取卡片处于灰锁状态的数据
{
	getCard();
	var re = cardCom.getLockProof(hCard,pin);
	if(re!="6985")re=evalCardReturn(re);
	if(re.substr(0,2)=="01")
	{
		var data={}
		data.offOnlineNo = parseInt(re.substr(14,4),16);
		return data;
	}
	else
		throw new Error("卡片处于正常状态");	
}

function getLockLoyaltyProofData(pin)  //读取卡片处于积分灰锁状态的数据
{	
	getLYApp();
	var re = cardCom.getLockLoyatyProof(hCard,pin);
	if(re!="6985")re=evalCardReturn(re);
	if(re.substr(0,2)=="01")
	{
		var data={}
		data.offOnlineNo = parseInt(re.substr(20,4),16);
		return data;
	}
	else
		throw new Error("卡片处于正常状态");	
}


function getLockLoyatyProof(pin)  //读取卡片是否处于积分灰锁状态
{
	getLYApp();
	var re = cardCom.getLockLoyatyProof(hCard,pin);
	if(re!="6985")re=evalCardReturn(re);
		if(re.substr(0,2)=="01")
		return true;
		else
		return false;
	
}

function initGreyUnlock(pin)  //联机解扣初始化
{
		if(!getLockProof(pin))
		{
			throw new Error("卡片处于正常状态,不可以联机解扣"); //抛出异常
		}
		var re = evalCardReturn(cardCom.initGreyUnlock(hCard,pin));
		var greydata = {}
		greydata[CARD_ITEMS[4][0]] = parseInt(re.substr(0,8),16);  //余额	4
		greydata[CARD_ITEMS[8][0]] = parseInt(re.substr(8,4),16);//脱机交易序号	2
		greydata[CARD_ITEMS[9][0]] = parseInt(re.substr(12,4),16);//联机交易序号	2
		greydata[CARD_ITEMS[10][0]] = re.substr(20,8); //伪随机数(ICC)	4
		greydata[CARD_ITEMS[11][0]] = re.substr(28,8); //MAC数据	4
		
		return greydata
}

function initGreyLoyatyUnlock(pin)  //联机积分解扣初始化
{
		getLYApp();
		if(!getLockLoyatyProof(pin))
		{
			throw new Error("卡片处于正常状态,不可以联机积分解扣"); //抛出异常
		}
		var date = evalCardReturn(cardCom.getLockLoyatyProof(hCard,pin)).substr(6,6);
		var re = evalCardReturn(cardCom.initGreyLoyatyUnlock(hCard,pin));
		var greydata = {}
		greydata[CARD_ITEMS[4][0]] = parseInt(re.substr(0,8),16);  //余额	4
		greydata[CARD_ITEMS[8][0]] = parseInt(re.substr(8,4),16);//脱机交易序号	2
		greydata[CARD_ITEMS[9][0]] = parseInt(re.substr(12,4),16);//联机交易序号	2
		greydata[CARD_ITEMS[10][0]] = re.substr(20,8); //伪随机数(ICC)	4
		greydata[CARD_ITEMS[11][0]] = re.substr(28,8); //MAC数据	4
		greydata[CARD_ITEMS[38][0]] = date;
		return greydata
}

function greyUnlock(money,resultMap) //联机解扣
{
	return evalCardReturn(cardCom.greyUnlock(hCard,money,resultMap.serverTime.substring(0,8),resultMap.serverTime.substring(8),resultMap.mac2.toUpperCase())).substr(0,8);	
}

function greyLoyaltyUnlock(money,resultMap) //积分联机解扣
{
	return evalCardReturn(cardCom.greyLoyaltyUnlock(hCard,money,resultMap.serverTime.substring(0,8),resultMap.serverTime.substring(8),resultMap.mac2.toUpperCase())).substr(0,8);	
}
/**
	getCardDetail
	@param options:disBalance|disLoyalty|disAppInfo|disPersonInfo|grayStatus
*/
function getCardDetail(options){
	var data = {};
	var psamData = {};
	var addData = {};
	var pin = defaultPin;
	//是PSAM卡，只返回卡内信息
	if(options.isPsam == true){
		psamData = getPsamTN();
		data[CARD_ITEMS[0][0]] = psamData.PsamSN;						//卡号
		data.PsamTN = psamData.PsamTN;									//PSAM终端号
		data.PsamSN = psamData.PsamSN;									//PSAM卡号
	}
	//不是PSAM卡，返回卡内和后台信息
	else{
		getCard();
		data[CARD_ITEMS[0][0]] = getAsn();									//卡号
		data[CARD_ITEMS[30][0]] = getPublicInfo(hCard)[CARD_ITEMS[30][0]];	//有效期
		var addData = getApplicationInfo();									//应用信息
		data[CARD_ITEMS[37][0]] = addData.pinFunction;						//是否启用Pin
	}
	if(options.disAppInfo == true){										//显示限制信息
		if(addData)
			data = Card.merge(data,addData);
	}
	if(options.disPersonInfo == true){
		var addData = getCardPersonInfo();								//个人信息
		if(addData)
			data = Card.merge(data,addData);
	}
	if(options.disBalance == true){
		if(data[CARD_ITEMS[37][0]] != "0"){
			pin = CardMgnt.inputCardPin();
			if (!pin) throw new Error("密码输入被取消！")
			data.cardPin = pin
		}
		if(pin  == null)return false;
		data[CARD_ITEMS[32][0]] = pin
		data[CARD_ITEMS[4][0]] = getCardBalance(pin);					//卡余额
		if (options.grayStatus)
			data.grayFund = getLockProof(pin);
	}
	if(options.disLoyalty == true){
		if(options.tradeDate)
		data[CARD_ITEMS[5][0]] = getLoyaltyBalance(options.tradeDate);	//卡积分余额
		if (options.grayStatus)
			data.grayPoint = getLockLoyatyProof(pin);
	}
	return data;
}
function getPinApp() //获取PIN码功能支持标识
{
	var re = getApplicationInfo();
	return re.pinFunction ;	
}

function updatePinApp(p,pin)//修改PIN码功能支持标识
{
	if(p.length!=2)
	{
		throw new Error("PIN码功能支持标识,请输入00-FF");
	}
	var rnd = getRandom(); //获取随机数
	var asn = getAsn();
	rnd=rnd.substring(0,8).toUpperCase();
	var re = getApplicationInfo("updatePinApp");
	p = F(p,2);
	if (!re.petroLimit) re.petroLimit = Constants.OIL_FULL
	if (!re.goodLimit) re.goodLimit = Constants.MER_FULL
	var data = formatAppInfo(re.petroLimit,re.goodLimit,re.oneDayTimesLimit,re.oneDayAmountLimit,re.oneDayNumLimit,re.oneTimesNumLimit,re.frequencyLimit,re.carNoLimit,p,re.accountCode,re.invoiceKind,re.unitCode,re.issuerCity,re.areaLimit,re.whiteLimit);
	var ret = DWR.syncCall('pbocService.formatCarNumber',asn,rnd,data);
	updateAppInfo(pin,ret.data,ret.macData);
}

function updateValid(date,pin) //修改公共信息中的"应用有效日期",同时修改2个应用
{
//钱包应用
	getPGApp();
	var asn = getAsn();
	var rnd = getRandom(); //获取随机数	
	rnd=rnd.substring(0,8).toUpperCase();
	//先读
	var re = evalCardReturn(cardCom.getPublicInfo(hCard));
	var b1 = re.substring(0,48);
	var b2 = re.substring(48,56);
	var b3 = re.substring(56,60);
	b2 = date ; //替换掉有效期	
	//后写	
	var cardData = b1+b2+b3;
	var mac = DWR.syncCall('pbocService.updateValid',asn,cardData,rnd);
	evalCardReturn(cardCom.updateValid(hCard,pin,cardData,mac.toUpperCase()));
	/*
//积分应用		
	getLYApp();
	asn = getAsn();
	rnd = getRandom(); //获取随机数	
	rnd=rnd.substring(0,8).toUpperCase();
	//先读
	re = evalCardReturn(cardCom.getPublicInfo(hCard));
	b1 = re.substring(0,48);
	b2 = re.substring(48,56);
	b3 = re.substring(56,60);
	b2 = date ; //替换掉有效期	
	//后写	
	cardData = b1+b2+b3;
	var mac = DWR.syncCall('pbocService.updateValid',asn,cardData,rnd);
	evalCardReturn(cardCom.updateValid(hCard,pin,cardData,mac.toUpperCase()));
	*/
}

function startUsePin(pin){
	updatePinApp(USE_PIN,pin);
}
function stopUsePin(pin){
	updatePinApp(NOT_USE_PIN,pin);
}
function getNeedPin(){
	var usePinFlag = getPinApp();
	return (usePinFlag == USE_PIN);
}

function writeFile(strKey,strContent)
{
	cardCom.writeTX(strKey,strContent);	
}

function readFile(strParam) //读文件
{
	var content = cardCom.readTX(strParam);
	if(content=="err1")
		{
			throw new Error("readfileerr");
		}	
	else if (content=="err2"){
		return "";
	}else
	{
		return content;
	}
}

function bigNumToBinary(num)
{
	var b="";
	for(var i=0,j=0;i<num.length;i++,j++)
	{		
		if(j%2==0&&j<num.length)
		{
			b=String(b)+String(hextobinary(num.substr(j,2),8));
		}
	}
	return b;
}

function chechactivex()
{
		try{
			var testCom = new ActiveXObject("COMLOADCTRL.LoadCtrl");　//创建对象
			cardCom.setKeyIndex(KEY_INDEX);//设置密钥索引
			cardCom = testCom;
			return true;
		}catch(e)
		{
			return false;
		}
}

function checkreader()
{  
	   var r= String(cardCom.checkReader());
	   if(r.substr(0,2)!="00")
	   		return false
	   else
	   		return true	    	
}

function testReadCard()
{
	 try{
	   	 getCard();
		 showInformation("读卡正常！");
	   }catch(e)
	   {
	   		showWarning("读卡异常！");
	   }
}

function checkDriver()
{	
	   var r= String(cardCom.checkDriver());
	   if(r.substr(0,2)!="00")
	   		return false
	   else
	   		return true
}

function checkPinPad()
{	
	   var r= String(cardCom.checkPinPad());
	   if(r.substr(0,2)!="00")
	   		return false
	   else
	   		return true
}

function handInstallDriver()
{
	  var r= String(cardCom.handInstallDriver());
	   if(r.substr(0,2)!="00")
	   		showWarning("驱动文件已经存在：\"C:\\Omnikey\\CardMan5x21 PCSC driver V1.1.2.4\"");

}

function setPinPadPort(com)
{	
	cardCom.setPinPanPort(parseInt(com));
	
}

function getPinPadPort()
{
	
	return cardCom.getPinPadPort();
	
}

function checkClient()
{	
	//检查驱动文件是否存在
		//检测读卡器是否能使用
		//检测密码键盘是否能用
		//提供手动下载控件安装包		
		if(chechactivex())
		{
			$("test1").innerHTML="<font color=green size=16>√</font>";
			$("warning").innerHTML="";
		}
		else
		{
			$("test1").innerHTML="<font color=red size=16>×</font>";
			$("warning").innerHTML="<font color=red >&nbsp;请先安装控件再进行检测</font>";
			return;
		}
	
		port = getPinPadPort();	
		var s = $("selectPort").options;
		for(var i=0;i<s.length;i++)
		{
			if(s[i].value==port)
			{
				s[i].selected=true;
				s[i].text = s[i].text.substr(0,4)+"(当前)";
			}	
			else
			{
				s[i].text = s[i].text.substr(0,4);
			}		
		}
			
		if(checkDriver())
			$("test2").innerHTML="<font color=green size=16>√</font>"
		else
			$("test2").innerHTML="<font color=red size=16>×</font>"	
				

		if(checkreader())
			$("test3").innerHTML="<font color=green size=16>√</font>"
		else
			$("test3").innerHTML="<font color=red size=16>×</font>"	
			
			
		if(checkPinPad())
			$("test4").innerHTML="<font color=green size=16>√</font>"
		else
			$("test4").innerHTML="<font color=red size=16>×</font>"		
			
}

function testGetPin()
{
	try{
			getPin();
			showInformation("密码键盘正常！");		
		}catch(e)
		{
			showError(e.description);
		}	
	
}

Card.merge = function(rObj,newObj){
	if (typeof rObj != "object" || typeof newObj != "object") return null;
	for (prop in newObj){
		if(newObj.hasOwnProperty(prop)){
			rObj[prop] = newObj[prop]
		}
	}
	return rObj;
}
